import { Buffer } from 'buffer'
import file from '@system.file'
import texttoaudio from '@service.texttoaudio'
import fetch from '@system.fetch'

export function arrayBufferToBase64(arrayBuffer) {
  const base64Data = Buffer.from(arrayBuffer).toString("base64");
  return base64Data;
}

export function readArrayBufferFromUri(uri) {
  return new Promise((resolve, reject) => {
    file.readArrayBuffer({
      uri: uri,
      success: (data) => resolve(data.buffer),
      fail: reject
    })
  })
}

export function detectImageFromBase64(base64Images) {
  console.log('======3')
  return new Promise((resolve, reject) => {
    fetch.fetch({
      url: 'http://121.37.46.189:8012/api/batch_img',
      responseType: 'json',
      method: 'POST',
      data: {
        images: base64Images
      },
      success: (response) => {
        resolve(response.data.data)
      },
      fail: (data, code) => {
        console.log(data, code)
        console.log('======44')
        reject()
      }
    })
  })
}

export function tts(content) {
  return new Promise((resolve, reject) => {
    texttoaudio.speak({
      lang: 'zh_CN',
      content: content,
      pitch: 1,
      rate: 1,
      success: (data) => {
        console.log(`handling success`)
        resolve(data)
      },
      fail: (data, code) => {
        console.log(`handling fail, code = ${code}`)
        reject()
      }
    })
  })
  
}